<?php

/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
class wms_ctl_admin_expressarapi extends desktop_controller
{
    //应收按月+客户+料品+单位【销售数量】汇总数量和金额；
    //应付快递费与服务费按月+料品+单位【销售数量】汇总数量和金额 

    function index()
    {

        $filter=array();
        $user = kernel::single('desktop_user');
        if($user->has_permission('wms_ctl_admin_expressarapi_sync'))
        {
            $actions= array(
                'new' => array(
                    'label' => '新建',
                    'href' => 'index.php?app=wms&ctl=admin_expressarapi&act=add_expressarapi',
                        'target' => '_blank',
                ),
                'confirm' => array(
                    'label' => '过数',
                    'submit' => 'index.php?app=wms&ctl=admin_expressarapi&act=doConfirm',
                ),
                'delete' => array(
                    'label' => '删除',
                    'submit' => 'index.php?app=wms&ctl=admin_expressarapi&act=doDelete',
                ),
            );
        }
        $params = array(
            'title' => '应收快递费过数',
            'actions' => $actions,
            'base_filter' => $filter,
            //'base_filter' => '',
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag' => false,
            'use_buildin_recycle' => false,
            'use_buildin_export' => true ,
            'use_buildin_import' => false,
            'use_buildin_filter' => true,
            'allow_detail_popup' => true,
            'max_actions' => 8,
            'use_view_tab' => false,
            'orderBy' => 'create_time desc',
        );
        $this->finder('wms_mdl_expressarapi', $params);
    }
    //添加备货
    function add_expressarapi()
    {
        //add by ldward 20180515 改造查询
        $sql = 'SELECT distinct AXCustomer, customername FROM sdb_ome_shop where AXCustomer!="" and JSType="0" order by AXCustomer';
        $shop_customer = kernel::database()->select($sql);
        foreach ($shop_customer as $key => $value) {
            $shops[]=array('AXCustomer'=>$value['AXCustomer'],'customername'=>'【'.$value['AXCustomer'].'】'.$value['customername']);
        }
        $this->pagedata['customerlist'] = $shops;
        $operator = kernel::single('desktop_user')->get_name();
        $this->pagedata['expressarapi']['inter_time'] =date('Y-m-d',time()) ;
        $this->pagedata['expressarapi']['operator'] = $operator;
        $this->pagedata['expressarapi']['arapi_bn']=$this->autocreatebn();
        $this->singlepage('admin/expressarapi/expressar_add.html');
    }
    function autocreatebn()
    {
        $bn='';
        $y = date("Y");
        $m = date("m");
        $d = date("d");
        $time_begin= mktime(0,0,0,$m,$d,$y);
        $time_end= mktime(23,59,59,$m,$d,$y);
        $delivery_model = $this->app->model('expressarapi');
        $filter['create_time|between'] = array($time_begin, $time_end);
        $delivery= $delivery_model->getList('arapi_bn',$filter,0,1,'create_time desc');
        if($delivery[0]['arapi_bn']=='')
        {
            $bn ='AR'.date('Ymd',time()).'01';
        }
        else
        {
            $bn=substr($delivery[0]['arapi_bn'] , 10 , 2);
            $num=intval($bn)+1;
            if($num<=9)
            {
                $bn ='AR'.date('Ymd',time()).'0'.$num;
            }else
            {
                $bn ='AR'.date('Ymd',time()).$num;
            }
        }
        return $bn;
    }
    function getdetails()
    {
        $data=$_GET;
        $begin = strtotime($data['begin_date']);
        $end = strtotime($data['end_date'])+86399;
        $AXCustomer = $data['AXCustomer'];
        $sql="SELECT * from (SELECT ifnull(f.AXCustomer,'no') AXCustomer,d.ax_shopname customername,items.bn,items.product_name,ext.unit,IFNULL(sum(items.number),0) saleqty,IFNULL(sum(items.sale_price),0) salemny,IFNULL(sum(e.lmfee),0) lmfee
                from  sdb_wms_deliverycomp a 
                inner join sdb_wms_deliverycomp_line b on a.id = b.deliverycomp_id
                inner join sdb_wms_deliverynote_line d on b.deliverynote_id = d.deliverynote_id
                inner join sdb_wms_delivery e on d.delivery_bn = e.delivery_bn  
                inner join sdb_wms_delivery_items items on e.delivery_id=items.delivery_id
                inner join sdb_ome_shop f on e.shop_id = f.shop_id
                inner JOIN sdb_ome_delivery od on ( e.outer_delivery_bn = od.delivery_bn )
                inner JOIN sdb_ome_delivery_order odo on ( od.delivery_id = odo.delivery_id )
                inner JOIN sdb_ome_orders os on (odo.order_id = os.order_id)
                inner JOIN sdb_material_basic_material_ext ext on items.product_id=ext.bm_id 
                where a.deliverycomp_time BETWEEN $begin and $end and f.JSType in('0') and f.AXCustomer!='' 
                and f.AXCustomer='$AXCustomer' and items.number>0
                group by f.AXCustomer,d.ax_shopname,items.bn,items.product_name,ext.unit)t ";

        $db = kernel::database();
        $rows= $db->select($sql);
        $i=0;
        foreach ($rows as $key => $value)
        {
            $items[$key]=$value;
            $items[$key]['product_id']=$i;
            $i=$i+1;
            
        }
        echo "window.autocompleter_json=".json_encode($items);
    }
    //保存备货通知单
    function doSave()
    {
        $this->begin('index.php?app=wms&ctl=admin_expressarapi&act=index');    
        $data=$_POST;
        $begin = strtotime($data['begin_date']);
        $end = strtotime($data['end_date'])+86399;  
        if($begin>$end)
        {
            $this->end(false, app::get('base')->_('结束时间小于开始时间，请确认！'));
        }
        $db = kernel::database();
        $sql="SELECT * from sdb_wms_expressarapi where begin_date<=$begin and $begin<end_date and AXCustomer='".$_POST['AXCustomer']."'";
        $rows= $db->select($sql);
        if(!empty($rows))
        {
            $this->end(false, app::get('base')->_('开始时间已存在区间，请确认日期！'));
        }
        $sql1="SELECT * from sdb_wms_expressarapi where begin_date<=$end and $end<end_date and AXCustomer='".$_POST['AXCustomer']."'";
        $rows1= $db->select($sql1);
        if(!empty($rows1))
        {
            $this->end(false, app::get('base')->_('结束时间已存在区间，请确认日期！'));
        }
        $sql2="SELECT * from sdb_wms_expressarapi where begin_date>=$begin and $end>=end_date and AXCustomer='".$_POST['AXCustomer']."'";
        $rows2= $db->select($sql2);
        if(!empty($rows2))
        {
            $this->end(false, app::get('base')->_('该区间已重复定义，请确认日期！'));
        }
        
        $expressarMdl = app::get('wms')->model('expressarapi');
        $expressarMdlL = app::get('wms')->model('expressarapi_line');
        $delivery_ID = $_POST['delivery_ID'];
        $memo = $_POST['memo'];
        $id=$_POST['id'];
        $operator = $_POST['operator'];
        if(empty($id)){
            $ar_id = $expressarMdl ->getList('id',array('arapi_bn'=>$_POST['purchase_name']));
            if ($ar_id) 
            {
                $this->end(false, '存在多人同时操作，请稍后重试');
            }
            $arr_order='';
            $arr_order['arapi']['arapi_bn']=$this->autocreatebn();//$_POST['purchase_name'];
            $arr_order['arapi']['remark']=$_POST['memo'];
            $arr_order['arapi']['operator']=$_POST['operator'];
            $arr_order['arapi']['AXCustomer']=$_POST['AXCustomer'];

            $sql = "SELECT distinct customername FROM sdb_ome_shop where AXCustomer='".$_POST['AXCustomer']."' ";
            $shop_customer = kernel::database()->select($sql);
            if(!empty($shop_customer))
            {
                $arr_order['arapi']['customername']=$shop_customer[0]['customername'];   
            }
            $arr_order['arapi']['booked_time']=strtotime($_POST['booked_time']);
            $arr_order['arapi']['inter_time']=strtotime($_POST['inter_time']);
            $arr_order['arapi']['create_time']=time();
            $arr_order['arapi']['begin_date']=$begin;
            $arr_order['arapi']['end_date']=$end;
            $res = $expressarMdl->insert($arr_order['arapi']);

        }else
        {
            $res=$id;
            kernel::database()->exec("delete from sdb_wms_expressarapi_line  where  arapi_id in(" . $id . ");");
        } 
        foreach ($delivery_ID as $key => $value)
        {
            $arr_line='';
            $arr_line['arapi']['arapi_id']=$res;
            if(empty($value['AXCustomer']))
            {
                $arr_line['arapi']['AXCustomer']='无';   
            }else{
                $arr_line['arapi']['AXCustomer']=$value['AXCustomer'];   
            }
            $arr_line['arapi']['customername']=$value['customername'];
            $arr_line['arapi']['bn']=$value['bn'];
            $arr_line['arapi']['product_name']=$value['product_name'];
            $arr_line['arapi']['unit']=$value['unit'];
            $arr_line['arapi']['saleqty']=$value['saleqty'];
            $arr_line['arapi']['salemny']=$value['salemny'];
            $arr_line['arapi']['lmfee']=$value['lmfee'];
            $expressarMdlL->insert($arr_line['arapi']);
            unset($arr_line);
            
        }
        $this->end(true, '已完成');
    }

    function editexpressarapi()
    {
        $expressarapiMdl = $this->app->model('expressarapi');
        $expressarapi_datas = $expressarapiMdl->getList('*', array('id'=>$_GET['id']), 0, -1);

        //add by ldward 20180515 改造查询
        $sql = 'SELECT distinct AXCustomer, customername FROM sdb_ome_shop where AXCustomer!="" order by AXCustomer';
        $shop_customer = kernel::database()->select($sql);
        foreach ($shop_customer as $key => $value) {
            $shops[]=array('AXCustomer'=>$value['AXCustomer'],'customername'=>'【'.$value['AXCustomer'].'】'.$value['customername']);
        }
        $this->pagedata['customerlist'] = $shops;
        $this->pagedata['expressarapi'] = $expressarapi_datas[0];
        $this->pagedata['expressarapi']['begin_date'] =date('Y-m-d',$expressarapi_datas[0]['begin_date']) ;
        $this->pagedata['expressarapi']['end_date'] =date('Y-m-d',$expressarapi_datas[0]['end_date']) ;
        $this->singlepage('admin/expressarapi/expressar_edit.html');
    }

    function getEditProducts($po_id){
        if ($po_id == ''){
            $po_id = $_POST['p[0]'];
        }
        $sql="SELECT * from sdb_wms_expressarapi_line  where arapi_id=".$po_id;

        $db=kernel::database();
        $rows=$db->select($sql);  
        $i=0;
        foreach ($rows as $key => $value)
        {
            $items[$key]=$value;
            $items[$key]['product_id']=$i;
            $i=$i+1;
        }
        echo json_encode($items);
    }
    //提交动作
    function doConfirm()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_expressarapi&act=index");
        $this->_request    = kernel::single('base_component_request');
        $order_info        = $this->_request->get_post();
        $db=kernel::database();
        $expressarapiMdl = $this->app->model('expressarapi_line');
        if ($order_info['isSelectedAll']=='_ALL_') 
        {
            foreach ($orders as $key_o => $order) 
            {
                $value = $order['id']; 

                $msg=$this->doSendAxar($value);
                if($msg=="0")
                {
                    $this->end(true, '过数成功！');
                }else{
                    $this->end(false, $msg);
                }
            }
        }else
        {
            $input = file_get_contents("php://input");
            $input_array = explode('&', $input);
            $number = count($input_array);
            if ($number > $max_input_vars) {
                $msg =  "多选不能超过系统表单最大提交数【".$max_input_vars."】条";
                $this->end(false, $msg);
            }
            foreach ($order_info['id'] as $key_o => $value)
            {

                $msg=$this->doSendAxar($value);
                if($msg=="0")
                {
                    $this->end(true, '过数成功！');
                }else{
                    $this->end(false, $msg);
                }
            }
        }      //
        $this->end(true, '已完成');
    }
    //确认动作
    function doDelete()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_expressarapi&act=index");
        $this->_request    = kernel::single('base_component_request');
        $order_info        = $this->_request->get_post();

        $expressarapi_model = $this->app->model('expressarapi');

        if ($order_info['isSelectedAll']=='_ALL_') 
        {
            foreach ($orders as $key => $order) 
            {
                $value = $order['id'];
                $orders = $expressarapi_model->getList('*', array('id'=>$value), 0, -1);
                if ($order[0]['status'] == 'unconfirmed') 
                {
                    $expressarapi_model->db->exec("delete from sdb_wms_expressarapi_line where arapi_id in(".$value . ");");
                    $expressarapi_model->db->exec("delete from sdb_wms_expressarapi  where  id in(" . $value . ");");
                } else {
                    $this->end(false, '过数单号【' . $order['expressarapi_bn'] . '】状态已同步，删除失败！');
                }
            }
        } else {
            $input = file_get_contents("php://input");
            $input_array = explode('&', $input);
            $number = count($input_array);
            if ($number > $max_input_vars) {
                $msg =  "多选不能超过系统表单最大提交数【".$max_input_vars."】条";
                $this->end(false, $msg);
            }
            foreach ($order_info['id'] as $key_o => $value) {
                $orders = $expressarapi_model->getList('*', array('id' => $value), 0, 1);

                if ($orders[0]['status'] == 'unconfirmed') 
                {
                    $expressarapi_model->db->exec("delete from sdb_wms_expressarapi_line where arapi_id in(" . $value . ");");
                    $expressarapi_model->db->exec("delete from sdb_wms_expressarapi where id in(" . $value . ");");
                } else {
                    $this->end(false, '过数单号【' . $order['expressarapi_bn'] . '】状态已同步，删除失败！');
                }
            }
        }
        $this->end(true, '已完成');
    }

    //快递费
    public function doSendAxar($id)
    {
        $msg='';
        $sql="SELECT * from sdb_wms_expressarapi a inner join sdb_wms_expressarapi_line b on a.id=b.arapi_id  where b.lmfee>0 and a.id=".$id;
        $rows = kernel::database()->select($sql);
        foreach ($rows as $key => $row) 
        {
            $param['list'][$key]['parmDocno'] = $row['arapi_bn'];//单号
            $param['list'][$key]['parmType'] = 1;//快递费类型，1应收、2应付
            $param['list'][$key]['parmMonth'] =date('Y-m',$row['begin_date']) ;//过数月份
            $param['list'][$key]['parminter_time'] =date('Y-m-d',$row['inter_time']) ;//过数日期
            $param['list'][$key]['parmbooked_time'] =date('Y-m-d',$row['booked_time']) ;//入账日期
            $param['list'][$key]['parmJSType'] = '';//结算类型，0代收代付、1理文支付
            $param['list'][$key]['parmCode'] = $row['AXCustomer'] ;//过数对象，客户、供应商
            $param['list'][$key]['parmAXCustomer'] = '';//应付过数到代办处
            $param['list'][$key]['parmBn'] = $row['bn'];//料号
            $param['list'][$key]['parmUnit'] = $row['unit'];//单位
            $param['list'][$key]['parmNumber'] = $row['saleqty'];//数量
            $param['list'][$key]['parmMny'] = $row['lmfee'];//运费
            $param['list'][$key]['parmServicesfee'] = 0;//服务费
            $param['list'][$key]['parmUniquelyIdentifies']=$row['arapi_bn'].$row['id'];
        }
        if (count($param['list']) > 0) 
        {
            try 
            {
                date_default_timezone_set("PRC");
                ini_set('soap.wsdl_cache_enabled', "0"); //关闭wsdl缓存
                ini_set('default_socket_timeout', 500);    // timeout
                if(WITH_QIMEN){
                    $res=kernel::single('erpapi_rpc_qimen')->call('InsSalesFreight',$param);
                    $res=json_decode($res,1);
                }else{
                    $webservice_url = HOST_AXToOMs;
                    $client = new SoapClient($webservice_url);
                    $res = $client->__soapCall('InsSalesFreight', array('parameters' => $param));
                    $res['response']['data'] = $res->InsSalesFreightResult;
                }
            error_log(date('Y-m-d H:i:s').'发送数据/'.var_export($param,true).'返回数据/'.var_export($res,true),3,DATA_DIR.'/logs/arapi'.date('Y-m-d').'.log');
                $res_msg = $res['response']['data'];
                if (isset($res_msg) && $res_msg == '0') 
                {
                    $data['status'] ='confirmed';
                    $data['id'] = $id;
                    app::get('wms')->model('expressarapi')->save($data);
                    $msg= "0";
                }else
                {
                    $msg=$res_msg;
                }
            } catch (Exception $e) {
                $msg=$e->getMessage();
            }
        } else {
            $msg = '无过数数据，请重新选择!';
        }
        return $msg;

    }
}


